
#import "JCHATChatViewController.h"
#import "JCHATChatTableViewCell.h"
#import "JCHATSendMessageViewController.h"


@interface JCHATChatViewController ()
{
    __block NSMutableArray *_conversationArr;
    NSInteger _unreadCount;
    UILabel *titleLabel;
}
@end


@implementation JCHATChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(netWorkConnectClose)
                                                 name:kJPFNetworkDidCloseNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(netWorkConnectSetup)
                                                 name:kJPFNetworkDidSetupNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(connectSucceed)
                                                 name:kJPFNetworkDidLoginNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(isConnecting)
                                                 name:kJPFNetworkIsConnectingNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reveiveMessageNotifi:)
                                                 name:JMSGNotification_ReceiveMessage object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(alreadyLoginClick)
                                                 name:kLogin_NotifiCation object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(creatGroupSuccessToPushView:)
                                                 name:kCreatGroupState
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(skipToSingleChatView:)
                                                 name:kSkipToSingleChatViewState
                                               object:nil];
    
    
    self.navigationController.navigationBar.barTintColor =kNavigationBarColor;
    self.navigationController.navigationBar.translucent = NO;
    
    NSShadow *shadow = [[NSShadow alloc]init];
    shadow.shadowColor = [UIColor colorWithRed:0 green:0.7 blue:0.8 alpha:1];
    shadow.shadowOffset = CGSizeMake(0,0);
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor whiteColor], NSForegroundColorAttributeName,
                                                                     shadow,NSShadowAttributeName,
                                                                     [UIFont boldSystemFontOfSize:18], NSFontAttributeName,
                                                                     nil]];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.chatTableView setBackgroundColor:[UIColor whiteColor]];
    self.chatTableView.dataSource=self;
    self.chatTableView.delegate=self;
    self.chatTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"会话";
    self.navigationItem.titleView = titleLabel;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveNotificationSkipToChatPageView:)
                                                 name:KApnsNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getConversationList)
                                                 name:JMSGNotification_ConversationInfoChanged
                                               object:nil];
    
}

- (void)skipToSingleChatView :(NSNotification *)notification {
    JMSGUser *user = [[notification object] copy];
    JCHATSendMessageViewController *sendMessageCtl =[[JCHATSendMessageViewController alloc] init];
    if ([self getConversationWithTargetId:user.username]) {
        sendMessageCtl.conversation = [self getConversationWithTargetId:user.username];
    }else {
        sendMessageCtl.user = user;
    }
    sendMessageCtl.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:sendMessageCtl animated:YES];
}

- (JMSGConversation *)getConversationWithTargetId:(NSString *)targetId {
    for (NSInteger i=0; i< [_conversationArr count]; i++) {
        JMSGConversation *conversation = [_conversationArr objectAtIndex:i];
        if ([conversation.targetId isEqual:targetId]) {
            return conversation;
        }
    }
    return nil;
}

- (void)reloadConversationInfo:(JMSGConversation *)conversation {
    DDLogDebug(@"Action - creatGroupSuccessToPushView - %@", conversation);
    for (NSInteger i=0; i<[_conversationArr count]; i++) {
        JMSGConversation *conversationObject = [_conversationArr objectAtIndex:i];
        if ([conversationObject.Id isEqualToString:conversation.Id]) {
            [_conversationArr removeObjectAtIndex:i];
            [_conversationArr insertObject:conversation atIndex:i];
            [_chatTableView reloadData];
            return;
        }
    }
}

#pragma mark --创建群成功Push group viewctl
- (void)creatGroupSuccessToPushView:(NSNotification *)object{
    DDLogDebug(@"Action - creatGroupSuccessToPushView - %@", object);
    JCHATSendMessageViewController *sendMessageCtl =[[JCHATSendMessageViewController alloc] init];
    sendMessageCtl.hidesBottomBarWhenPushed=YES;
    sendMessageCtl.conversation = (JMSGConversation *)[object object];
    [self.navigationController pushViewController:sendMessageCtl animated:YES];
}

- (void)receiveNotificationSkipToChatPageView:(NSNotification *)notification {
    DDLogDebug(@"Action - receiveNotificationSkipToChatPageView - %@", notification);
    JCHATSendMessageViewController *sendMessageCtl;
    for (UIViewController *ctl in self.navigationController.childViewControllers) {
        if ([ctl isKindOfClass:[JCHATSendMessageViewController class]]) {
            return;
        }
    }
    if (!sendMessageCtl) {
        sendMessageCtl =[[JCHATSendMessageViewController alloc] init];
    }
    sendMessageCtl.hidesBottomBarWhenPushed = YES;
    sendMessageCtl.conversation.chatType = kJMSGSingle;
    NSDictionary *apnsDic = [notification object];
    NSString *targetName = [apnsDic[@"aps"] objectForKey:@"alert"];
    if ([targetName isEqualToString:[JMSGUser getMyInfo].username]) {
        return;
    }
    __block JMSGConversation *conversation;
    for (NSInteger i =0; i<[_conversationArr count]; i++) {
        JMSGConversation *getConversation = [_conversationArr objectAtIndex:i];
        if ([getConversation.targetId isEqualToString:[[targetName componentsSeparatedByString:@":"] objectAtIndex:0]]) {
            conversation = getConversation;
        }
    }
    if (!conversation) {
        [JMSGConversation createConversation:targetName withType:kJMSGSingle completionHandler:^(id resultObject, NSError *error) {
            conversation = (JMSGConversation  *)resultObject ;
            JPIMMAINTHEAD(^{
                sendMessageCtl.conversation = conversation;
                [self.navigationController pushViewController:sendMessageCtl animated:YES];
            });
            NSInteger badge = _unreadCount - [conversation.unreadCount integerValue];
            [self saveBadge:badge];
            [conversation resetUnreadMessageCountWithCompletionHandler:^(id resultObject, NSError *error) {
                if (error == nil) {
                    DDLogDebug(@"消息清零成功");
                }else {
                    DDLogDebug(@"消息清零失败");
                }
            }];
        }];
        return;
    }
    sendMessageCtl.conversation = conversation;
    [self.navigationController pushViewController:sendMessageCtl animated:YES];
    NSInteger badge = _unreadCount - [conversation.unreadCount integerValue];
    [self saveBadge:badge];
}

- (void)netWorkConnectClose {
    titleLabel.text =@"未连接";
}
- (void)netWorkConnectSetup {
    titleLabel.text =@"收取中...";
}
- (void)connectSucceed {
    titleLabel.text =@"会话";
}
- (void)isConnecting {
    titleLabel.text =@"连接中...";
}


#pragma mark --收到消息
- (void)reveiveMessageNotifi :(NSNotification *)notifi {
    [self getConversationList];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    [self getConversationList];
}

- (void)getConversationList {
    [JMSGConversation getConversationListWithCompletionHandler:^(id resultObject, NSError *error) {
        JPIMMAINTHEAD(^{
            if (error == nil) {
                _conversationArr = [self sortConversation:resultObject];
                _unreadCount = 0;
                for (NSInteger i=0; i < [_conversationArr count]; i++) {
                    JMSGConversation *conversation = [_conversationArr objectAtIndex:i];
                    _unreadCount = _unreadCount + [conversation.unreadCount integerValue];
                }
                [self saveBadge:_unreadCount];
            }else {
                _conversationArr = nil;
            }
            [self.chatTableView reloadData];
        });
    }];
}

NSInteger sortType(id object1,id object2,void *cha) {
    JMSGConversation *model1 = (JMSGConversation *)object1;
    JMSGConversation *model2 = (JMSGConversation *)object2;
    if([model1.latestDate integerValue] > [model2.latestDate integerValue]) {
        return NSOrderedAscending;
    }else if([model1.latestDate integerValue] < [model2.latestDate integerValue]) {
        return NSOrderedDescending;
    }
    return NSOrderedSame;
}

#pragma mark --排序conversation
- (NSMutableArray *)sortConversation:(NSMutableArray *)conversationArr {
    NSArray *sortResultArr = [conversationArr sortedArrayUsingFunction:sortType context:nil];
    return [NSMutableArray arrayWithArray:sortResultArr];
}
- (void)alreadyLoginClick {
    [self getConversationList];
}


//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

//先设置Cell可移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    JMSGConversation *conversation = [_conversationArr objectAtIndex:indexPath.row];
    // FIXME 这里要考虑单聊、群聊
    [JMSGConversation deleteConversation:conversation.targetId
                                withType:kJMSGSingle
                       completionHandler:^(id resultObject, NSError *error) {
                           if (error == nil) {
                               DDLogDebug(@"delete conversation success");
                           }else {
                               DDLogDebug(@"delete conversation error");
                           }
                       }];
    [conversation deleteAllMessageWithCompletionHandler:^(id resultObject, NSError *error) {
    }];
    [_conversationArr removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([_conversationArr count] > 0) {
        return [_conversationArr count];
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"chatCell";
    JCHATChatTableViewCell *cell = (JCHATChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[JCHATChatTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    JMSGConversation *conversation =[_conversationArr objectAtIndex:indexPath.row];
    [cell setCellDataWithConversation:conversation];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (kApplicationHeight <=480 ) {
        return 65;
    }
    return 80;
}


//响应点击索引时的委托方法
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [_conversationArr count];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    JCHATSendMessageViewController *sendMessageCtl =[[JCHATSendMessageViewController alloc] init];
    sendMessageCtl.hidesBottomBarWhenPushed=YES;
    sendMessageCtl.conversation.chatType = kJMSGSingle;
    JMSGConversation *conversation =[_conversationArr objectAtIndex:indexPath.row];
    sendMessageCtl.conversation = conversation;
    [self.navigationController pushViewController:sendMessageCtl animated:YES];
    
    NSInteger badge = _unreadCount - [conversation.unreadCount integerValue];
    [self saveBadge:badge];
}

- (void)saveBadge:(NSInteger)badge {
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%zd",badge] forKey:kBADGE];
    [[NSUserDefaults standardUserDefaults] synchronize];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
